package com.apex.oauth.security.ice.filter;

import com.apex.common.util.DigestUtil;
import com.apex.common.util.JsonUtils;
import com.apex.oauth.security.domian.UserLoginDomain;
import com.apex.oauth.security.ice.granted.Openid;
import com.apex.oauth.security.util.ICECookieUtil;
import com.apex.security.api.entity.TUser;
import com.wiscom.is.IdentityFactory;
import com.wiscom.is.IdentityManager;
import com.wiscom.is.SSOToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class IceInterceptor implements HandlerInterceptor {

    @Value("${weix.open:false}")
    private boolean isOpenWeiXin;

    @Value("${sso.type:none}")
    private String type;

    @Value("${sso.ice.file.path:/EDU}")
    private String filePath;

    @Value("${sso.ice.domain:.suda.edu.cn}")
    private String iceDomain;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        SecurityContextImpl securityContextImpl = (SecurityContextImpl) httpServletRequest
                .getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        Device currentDevice = DeviceUtils.getCurrentDevice(httpServletRequest);
        if (null != securityContextImpl) {
            String password = null;
            String userName = null;
            if (securityContextImpl.getAuthentication() != null) {
                password = (String) securityContextImpl.getAuthentication().getCredentials();
                userName = securityContextImpl.getAuthentication().getName();
            }
            if (!StringUtils.isEmpty(password) && !StringUtils.isEmpty(userName)) {
                List<Openid> list= (List<Openid>) securityContextImpl.getAuthentication().getAuthorities();
                String openid="";
                if(null!=list&&list.size()>1){
                    openid=list.get(1).getAuthority();
                }
                /****开启微信****/
                if (isOpenWeiXin) {
                    if (!currentDevice.isNormal()) {//非pc端访问
                        ICECookieUtil.addWeiXinCookie(httpServletResponse, iceDomain, DigestUtil.md5(openid+password));
                    }
                }
                if ("ice".equals(type)) {
                    IdentityFactory factory = IdentityFactory.createFactory(filePath);
                    IdentityManager im = factory.getIdentityManager();
                    SSOToken token = im.createStoken(userName, password);
                    ICECookieUtil.addCookie(httpServletResponse, iceDomain, token.getTokenValue());
                    ((CredentialsContainer) securityContextImpl.getAuthentication()).eraseCredentials();//清除密码
                }
            }

            TUser user = (TUser) httpServletRequest.getSession().getAttribute("SESSION_USER_BEAN");
            if (!StringUtils.isEmpty(userName)) {
                if (null == user&&!StringUtils.isEmpty(userName)) {
                    TUser tUser=new TUser();
                    tUser.setUserid(userName);
                    httpServletRequest.getSession().setAttribute("SESSION_USER_BEAN", user);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
